package com.authentication.manager;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.DeferredSecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class SecurityContextRepositoryAuthenticationManager implements AuthenticationManager {

    private final SecurityContextRepository securityContextRepository;

    public SecurityContextRepositoryAuthenticationManager(SecurityContextRepository securityContextRepository) {
        this.securityContextRepository = securityContextRepository;

    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();


        DeferredSecurityContext deferredSecurityContext = securityContextRepository.loadDeferredContext(servletRequestAttributes.getRequest());

        if (deferredSecurityContext != null) {
            return deferredSecurityContext.get().getAuthentication();
        }

        return null;
    }
}
